package sif.Activity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sif.Activity.MyFriendActivity.MyArrayAdapter;
import sif.Entity.Friend;
import sif.Entity.NewFeed;
import sif.FacebookSDK.AsyncFacebookRunner;
import sif.FacebookSDK.FacebookError;
import sif.FacebookSDK.AsyncFacebookRunner.RequestListener;
import sif.PullToRefreshListView.PullToRefreshListView;
import sif.Static.FacebookObjects;
import sif.Static.SaveData;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class NewFeedActivity extends Activity {

	AsyncFacebookRunner asyncFbRunner;
	List<NewFeed> newFeedObjects;
	PullToRefreshListView pullToRefreshListView;
	NewFeedAdapter myArrayAdapter;
	String next_paging = null;
	
	
	FacebookObjects fbObjects;
	ProgressDialog pd;
	
	public final int LOADING_NEW_FEED = 1;
	public final int LOADING_MORE_NEW_FEED = 2;
	
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == LOADING_NEW_FEED) {
				pd.dismiss();
				Log.i("load new feeds", "Prepare");

				if (newFeedObjects.size() > 0) {
					Log.i("load list friends", "OK");
					myArrayAdapter = new NewFeedAdapter(
							NewFeedActivity.this, R.layout.row_new_feed,
							newFeedObjects);
					pullToRefreshListView.setAdapter(myArrayAdapter);
				}
			} 
			else if (msg.what == LOADING_MORE_NEW_FEED) {
				if (newFeedObjects.size() > 0) {
					myArrayAdapter.notifyDataSetChanged();
				}
			}
		}

	};
	
	public void initComponents(){
		pd = new ProgressDialog(this);
		fbObjects = FacebookObjects.getFacebookObjects();
		pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);
		
		newFeedObjects = new ArrayList<NewFeed>();
		
		String access_token = SaveData.getInstance(this).getAccessToken(); 
		long expires = SaveData.getInstance(this).getAccessExpire();

		if (access_token != null) {
			fbObjects.getFacebook().setAccessToken(access_token);

			Log.d("FB Sessions", "" + fbObjects.getFacebook().isSessionValid());
		}

		if (expires != 0) {
			fbObjects.getFacebook().setAccessExpires(expires);
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friends_list);
		
		initComponents();
		
		pd.setMessage("Loading...");
		pd.show();
		
		asyncFbRunner = fbObjects.getAsyncRunner();
//		next_paging = "https://graph.facebook.com/100000166932128/home?limit=1&value=1&base_amount=1&format=json&access_token=BAAD6suxQ3sYBAK8yUdQrhYC8ii2VVPQqXJ4zYHgq0ZC9gmOcItwKSLiEIwMRbUQZB4ZBg9gPq0DJWZAG24IPx3OQLzXP8mKgxUSXFJQIbpXofUefyOQaSuVMornXgOKGGJ3aqpfcjwZDZD&until=1343239286";
		try {
			getNewFeeds();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pullToRefreshListView.setOnRefreshListener(new sif.PullToRefreshListView.PullToRefreshListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				try {
					getNewFeeds();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// Your code to refresh the list contents goes here

				// Make sure you call listView.onRefreshComplete()
				// when the loading is done. This can be done from here or any
				// other place, like on a broadcast receive from your loading
				// service or the onPostExecute of your AsyncTask.

				// For the sake of this sample, the code will pause here to
				// force a delay when invoking the refresh
				pullToRefreshListView.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						pullToRefreshListView.onRefreshComplete();
					}
				}, 0);
			}
		});
		
	}
	
	public Bundle getParamsFromFbUrl(String url){
		Bundle params = new Bundle();
		
		String[] urlArr = url.split("https://graph.facebook.com/(\\d)*/home\\?");
		String paramString = urlArr[urlArr.length-1];
		String[] paramPairArr = paramString.split("&");
		for(String pair : paramPairArr){
			if(!pair.contains("access_token")){	
				String[] paramArr = pair.split("=");
				//Put key and value of params to Bundle
				params.putString(paramArr[0], paramArr[1]);
			}			
		}				
		return params;
	}
	
	/**
	 * get your friends list
	 * */
	public void getNewFeeds() throws JSONException{
		Bundle params = new Bundle();
		if(next_paging != null){
			params = getParamsFromFbUrl(next_paging);
		}
		else{			
			params.putString("limit", "3");
		}
		asyncFbRunner.request("me/home", params, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("New Feeds", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject json_response = new JSONObject(json);

					JSONObject obj = json_response.getJSONObject("paging");
					next_paging = obj.getString("next");
					
					Log.i("thaile","next url : " + obj.getString("next"));
					Log.i("thaile", "previous url : " + obj.getString("previous"));
										
					JSONArray dataArr = json_response.getJSONArray("data");
					if(dataArr.length() > 0){
						for (int i = 0; i < dataArr.length(); i++) {
							JSONObject dataObj = dataArr.getJSONObject(i);
							
							Log.i("thaile", "this id : " + dataObj.getString("id"));
							Log.i("thaile", "id : " + dataObj.getJSONObject("from").getString("id"));
							Log.i("thaile", "from name : " + dataObj.getJSONObject("from").getString("name"));
							
							NewFeed newfeed = new NewFeed();
							newfeed.setId(dataObj.getJSONObject("from").getString("id"));
//							if(dataObj.getString("description") != null){
//								newfeed.setStory(dataObj.getString("description"));
//							}
							newfeed.setName(dataObj.getJSONObject("from").getString("name"));
							
							URL img_url = null;
							Bitmap avatar = null;
							try {
								img_url = new URL("https://graph.facebook.com/"
										+ dataObj.getJSONObject("from").getString("id") + "/picture");
								try {
									avatar = BitmapFactory.decodeStream(img_url
											.openConnection().getInputStream());
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								newfeed.setAvatar(avatar);
								
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							newFeedObjects.add(newfeed);
						}
						if(next_paging != null){
							handler.sendEmptyMessage(LOADING_NEW_FEED);
						}
						else{			
							handler.sendEmptyMessage(LOADING_MORE_NEW_FEED);
						}
					}		
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}
	
	class NewFeedAdapter extends ArrayAdapter<NewFeed> {

		public NewFeedAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
			// TODO Auto-generated constructor stub
		}

		public NewFeedAdapter(Context context, int textViewResourceId,
				List<NewFeed> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = convertView;
			if (v == null) {
				LayoutInflater inflater = getLayoutInflater();
				v = inflater.inflate(R.layout.row_new_feed, null);
			}
			TextView tvNameFrom = (TextView) v.findViewById(R.id.tvNameFrom);
			tvNameFrom.setText(this.getItem(position).getFromName());
			
			TextView tvMessage = (TextView) v.findViewById(R.id.tvStory);
			tvMessage.setText(this.getItem(position).getStory());
			
			ImageView ivAvatar = (ImageView) v
					.findViewById(R.id.ivAvatar);
						
			try {
				if(this.getItem(position).getAvatar() != null){
					ivAvatar.setImageBitmap(this.getItem(position).getAvatar());
				}	
			} catch (Exception e) {
				Log.i("thaile", "error : out_of_array_bound" + e.toString());
				ivAvatar.setImageResource(android.R.drawable.star_on);
			}
					
			return v;
		}

	}
}
